package com.shujia.flink.sql

import org.apache.flink.streaming.api.scala._
import org.apache.flink.table.api._
import org.apache.flink.table.api.bridge.scala._
import org.apache.flink.types.Row

object Demo3Window {
  def main(args: Array[String]): Unit = {

    val bsEnv: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment

    val bsSettings: EnvironmentSettings = EnvironmentSettings
      .newInstance()
      .useBlinkPlanner() //指定计划器为blink
      .inStreamingMode() //指定流模式
      .build()
    /**
      *
      * 构建flink table环境
      *
      */
    val bsTableEnv: StreamTableEnvironment = StreamTableEnvironment.create(bsEnv, bsSettings)


    /**
      * 创建source表
      *
      */

    bsTableEnv.executeSql(
      """
        |CREATE TABLE words_source (
        |  word STRING,
        |  ts AS PROCTIME()  -- 处理时间
        |) WITH (
        |  'connector' = 'kafka',
        |  'topic' = 'words',
        |  'properties.bootstrap.servers' = 'master:9092,node1:9092,node2:9092',
        |  'properties.group.id' = 'asdasd',
        |  'scan.startup.mode' = 'earliest-offset',
        |  'format' = 'csv',
        |  'csv.ignore-parse-errors' = 'true'
        |)
        |
      """.stripMargin)


    bsTableEnv.executeSql(
      """
        |CREATE TABLE count_sink (
        |  word STRING,
        |  win_start TIMESTAMP(3),
        |  c bigint
        |) WITH (
        |  'connector' = 'kafka',
        |  'topic' = 'count',
        |  'properties.bootstrap.servers' = 'master:9092,node1:9092,node2:9092',
        |  'properties.group.id' = 'asdasd',
        |  'format' = 'json'
        |)
        |
      """.stripMargin)


    /**
      * 统计过最近5秒单词的数量
      *
      */

    bsTableEnv.executeSql(
      """
        |
        |insert into count_sink
        |
        |select word,TUMBLE_START(ts, interval '5' SECOND) as win_start,count(1) as c
        |from words_source
        |group by  word,TUMBLE(ts, interval '5' SECOND)
        |
      """.stripMargin)



  }
}
